<template>
    <div class="user">
      <el-row>
          <el-col :span="24">
              <el-breadcrumb separator="/">
                  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                  <el-breadcrumb-item><a href="#">用户管理</a></el-breadcrumb-item>
                  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
              </el-breadcrumb>
          </el-col>
      </el-row>
      <el-row>
        <!-- 给组件绑定原生事件的话，需要一个.native的修饰符 -->
            <el-input placeholder="请输入内容"  class="input-with-select search-input" v-model="query"  @keyup.native.enter="initList">
              <el-button slot="append" icon="el-icon-search" @click="initList"></el-button>
            </el-input>
            <el-button type="success" plain @click="adddialogFormVisible = true">添加用户</el-button>
      </el-row>
      <el-table
        class="kkMagrin"
         v-loading="loading"
        :data="userlist"
        style="width: 100%">
          <el-table-column
              type="index"
              width="50">
          </el-table-column>
          <el-table-column
              prop="username"
              label="姓名"
              width="180">
          </el-table-column>
          <el-table-column
              prop="email"
              label="邮箱"
              width="180">
          </el-table-column>
          <el-table-column
              prop="mobile"
              label="手机号">
          </el-table-column>
          <el-table-column label="用户状态">
              <template slot-scope="scope">
                  <el-switch v-model="scope.row.mg_state" @change="changeUser(scope.row)">
                  </el-switch>
              </template>
        </el-table-column>
          <el-table-column label="操作">
              <template slot-scope="scope">
                  <el-button size="mini" type="primary" icon="el-icon-edit" plain @click="showeditUser(scope.row)"></el-button>
                  <el-button size="mini" type="danger" icon="el-icon-delete" plain @click="showdeleteUser(scope.row)"></el-button>
                  <el-button size="mini" type="warning" icon="el-icon-check" plain @click="showgrantUser(scope.row)"></el-button>
              </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page=1
              :page-sizes="[2, 4, 6, 8]"
              :page-size="1"
               layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
      </div>
      <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="adddialogFormVisible">
          <el-form :model="addform" :label-width="formLabelWidth" :rules="rules" ref="addformName">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addform.username" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="密 码" prop="password" >
              <el-input v-model="addform.password" auto-complete="off" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮 箱" prop="email">
              <el-input v-model="addform.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电 话" prop="mobile">
              <el-input v-model="addform.mobile" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="adddialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="adduserSubmit('addformName')">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
          <el-form :model="editform" :label-width="formLabelWidth" :rules="rules" ref="editformName">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editform.username" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="邮 箱" prop="email">
              <el-input v-model="editform.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="电 话" prop="mobile">
              <el-input v-model="editform.mobile" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="editdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="edituserSubmit()">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 删除用户 -->
      <el-dialog
        title="提示"
        :visible.sync="deletedialogVisible"
        width="30%"
        :before-close="handleClose">
        <span>确定要删除用户信息吗？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deletedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteuser()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 为用户分配角色 -->
       <el-dialog title="分配角色" :visible.sync="grantdialogFormVisible">
          <el-form :model="grantform" :label-width="formLabelWidth">
            <el-form-item label="用户名" prop="username">
              <el-tag type="info" >{{grantform.username}}</el-tag>
            </el-form-item>
            <el-form-item label="分配角色：">
            <el-select v-model="roleId" placeholder="分配角色：">
              <el-option 
              v-for = "role in roleList" :key="role.id"
              :label="role.roleName" :value="role.id"></el-option>
            </el-select>
            </el-form-item>
          </el-form>
         
          <div slot="footer" class="dialog-footer">
            <el-button @click="grantdialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="grantuserSubmit">确 定</el-button>
          </div>
        </el-dialog>
    </div>
</template>
<script>
import { getUserList,getChangeUser,getAddUser,getUserById,edituser,deleteUser,grantUser,allotgrantUser } from "@/api/index";
export default {
  data() {
    return {
      userlist: [],
      query:'',
      loading:true,
      total:0,
      pagesize:1,
      pagenum:1,
      adddialogFormVisible:false,
      editdialogFormVisible:false,
      deletedialogVisible:false,
      grantdialogFormVisible:false,
      addform:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
       editform:{
        username:'',
        email:'',
        mobile:'',
      },
      grantform:{

      },
      formLabelWidth:"100px",
      roleList:[],
      roleId:"",
      rules:{
         username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
           password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type:'email', message: '请输入正确的邮箱', trigger: 'blur' }
          ],
           mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
          ], 
      }
    };
  },
  created() {
    this.initList();
  },
  methods: {
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.initList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.initList();
    },
    initList() {
      this.loading = true;
      let params = { params: { query: this.query, pagenum: this.pagenum, pagesize: this.pagesize}};
      console.log(params);
      getUserList(params).then(res => {
        console.log(res);
        if(res.meta.status===200){
          this.userlist = res.data.users;
          this.total = res.data.total
        }else{
           this.$message({
                message:'获取用户列表失败',
                type:'error'
           })
        }
      });
      this.loading = false;
    },
      /* 添加用户信息 */
      adduserSubmit(formName){
        // console.log(123)
        this.$refs[formName].validate(validate=>{
          if(validate){
              getAddUser(this.addform).then(res=>{
              if(res.meta.status===201){
                this.$message({
                  message:'添加用户状态成功',
                  type:'success'
                });
                 this.adddialogFormVisible = false;
                 this.initList()
                /*  this.addform = {
                    username:'',
                    password:'',
                    email:'',
                    mobile:'',
                 } */
              }
            }) 
          }
        }) 
       
      },
      /* 获取用户信息 */
      showeditUser(row){
        console.log(row)
           this.editdialogFormVisible = true
             this.editform.username = row.username
             this.editform.email = row.email
             this.editform.mobile = row.mobile    
             this.editform.id = row.id    
      },
      /* 编辑用户信息 */
      edituserSubmit(){
        this.$refs.editformName.validate(validate=>{
              if(validate){
               edituser(this.editform).then(res=>{
               console.log(res,123)
               if(res.meta.status === 200){
                 this.$message({
                   type:'success',
                   message:'修改成功'
                 })
                 this.editdialogFormVisible = false;
                 this.initList();
               }
           }) 
              }
        })
          
      },
      /* 删除用户 */
        showdeleteUser(row){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser({id:row.id}).then(res=>{
            if(res.meta.status === 200){
              this.$message({
              type: 'success',
              message: '删除成功!'
            });
           this.initList();
           }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      /* 用户状态编辑 */
    changeUser(row){
      console.log(row)
      getChangeUser({uid:row.id,type:row.mg_state}).then(res=>{
      if(res.status === 200){
          this.$message({
          message: '修改用户状态成功',
          type: 'success'
        });
      }
     })
    },
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
       /* 显示用户分配角色对话框 */
      showgrantUser(row){
        this.grantform = row
        // console.log(row);
        this.grantdialogFormVisible = true;
        grantUser().then(res=>{
          // console.log(res,123);
          this.roleList = res.data;
        })
      },
      // 为用户分配角色修改用户角色
      grantuserSubmit(){
        if(!this.roleId){
          this.$message({
            type:'warning',
            message:'角色不能为空，请选择'
          })
        }else{
          allotgrantUser({id:this.grantform.id,rid:this.roleId}).then(res=>{
            if(res.meta.status == 200){
                this.$message({
                  type:'success',
                  message:'为用户分配角色成功'
              })
              this.grantdialogFormVisible = false
            }else{
                this.$message({
                  type:'error',
                  message:'为用户分配角色失败'
                })
            }
          })
        }
      
      }
  },
};
</script>
<style lang='scss' scoped>
.user {
  .kkMagrin{
    margin: 20px 0;
  }
  .search-input {
    width: 300px;
  }
  .page {
    padding: 5px 0;
    background-color: #d3dce6;
  }
}
</style>


 
